//
//  UIBarButtonItem+JwCate.m
//  JwPack
//
//  Created by 陈警卫 on 2022/8/20.
//

#import "UIBarButtonItem+JwCate.h"
#import "UIView+JwCate.h"
#import "NSString+JwUI.h"

@implementation UIBarButtonItem (JwCate)

/// 自定义 UIBarButtonItem
/// @param image 图标
+ (UIBarButtonItem *)jw_itemWithTarget:(id)target action:(SEL)action image:(NSString *)image {
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btn addTarget:target action:action forControlEvents:(UIControlEventTouchUpInside)];
    [btn setImage:[UIImage imageNamed:image] forState:(UIControlStateNormal)];
    [btn setImage:[UIImage imageNamed:image] forState:(UIControlStateHighlighted)];
    
    btn.jw_size = btn.currentImage.size;
    return [[UIBarButtonItem alloc] initWithCustomView:btn];
}

/// 自定义 UIBarButtonItem
/// @param image 图标
/// @param size 图标大小
+ (UIBarButtonItem *)jw_itemWithTarget:(id)target action:(SEL)action image:(NSString *)image size:(CGSize)size {
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btn addTarget:target action:action forControlEvents:(UIControlEventTouchUpInside)];
    [btn.widthAnchor constraintEqualToConstant:size.width].active = YES;
    [btn.heightAnchor constraintEqualToConstant:size.height].active = YES;
    btn.jw_size = size;
    [btn setImage:[UIImage imageNamed:image] forState:(UIControlStateNormal)];
    [btn setImage:[UIImage imageNamed:image] forState:(UIControlStateHighlighted)];
    
    return [[UIBarButtonItem alloc] initWithCustomView:btn];
}

/// 自定义 UIBarButtonItem
/// @param title 标题
/// @param color 标题颜色
/// @param image 图标
+ (UIBarButtonItem *)jw_itemWithTarget:(id)target action:(SEL)action title:(NSString *)title titleColor:(UIColor *)color image:(NSString *)image {
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [btn addTarget:target action:action forControlEvents:(UIControlEventTouchUpInside)];
    if (image) {
        [btn setImage:[UIImage imageNamed:image] forState:(UIControlStateNormal)];
        [btn setImage:[UIImage imageNamed:image] forState:(UIControlStateHighlighted)];
    }
    [btn setTitle:title forState:(UIControlStateNormal)];
    [btn setTitleColor:color forState:(UIControlStateNormal)];
    
    CGFloat space = 5;
    btn.titleLabel.font = [UIFont systemFontOfSize:17];
    if (image) {
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, space, 0, - space);
    }
    CGSize imgSize = btn.currentImage.size;
    UIFont *font = btn.titleLabel.font;
    CGFloat labw = [btn.currentTitle jw_widthForHeight:imgSize.height fontsize:font.pointSize];
    btn.jw_size = CGSizeMake(imgSize.width + labw + space, imgSize.height);
    
    return [[UIBarButtonItem alloc] initWithCustomView:btn];
}

@end
